<?php

require_once "../../maincore.php";
define('GRS_CONFIG_FILE', 'setting.php');
define('GRS_LOCALE_DIR', 'lang');

class GRS{
    
    private static $appConfig;
    private static $appMessage;
	
	function __construct(){
				
		//almacenar el array de setting.php a $appConfig
        self::$appConfig = include GRS_CONFIG_FILE;
        //almacenar el array de idioma indicado en config.php a $appMessage
        self::$appMessage = include GRS_LOCALE_DIR.'/'.$this->config('DefaultLocale').'.php';
	}
        
    //para optener valores de $appConfig
    public function config($key) {
        
        if (array_key_exists($key, self::$appConfig)){
            $configArr =  &self::$appConfig[$key];
            return $configArr;
        }else{
            return null;
        }
    }
    
    //para optener valores de $appMessage
    public function message($key) {
        
        if (array_key_exists($key, self::$appMessage)){
            $messageArr =  &self::$appMessage[$key];
            return $messageArr;
        }else{
            return "Unknow Message";
        }
    }
   
	public function params($key = null) {
		if(!$key)
			return $_REQUEST;
		
        if (array_key_exists($key, $_REQUEST)){
            $paramsArr =  &$_REQUEST[$key];
            return  $paramsArr;
        }else{
            return null;
        }
    }
    
    public function mergeParams($queryStr){
    	$querysArr = explode('&', urldecode($queryStr));
	
		$params = array();

		$i = 0;
		
		foreach($querysArr as $queryArr){
			$params[] = explode('=', $queryArr);
			
			$param = $params[$i][0];
			$value = $params[$i][1];
			
			$_REQUEST[$param] = $value;
			
			$i++;
		}	
    }
    
    public static function raise($message){
        throw new Exception($message);
    }
    
    public function url($page = null, $params = array())
    {        
        $queryString = '';
        
        if (count($params)) {
            $queryString .= '?';
            foreach ($params as $param => $value) {
                $queryString .= sprintf('%s=%s&', $param, urlencode($value));
            }
            $queryString = rtrim($queryString, '&');
        }
   
        if($page)
            $url = sprintf('%s%s', $page, $queryString);  
        else    
            $url = sprintf("%s", $queryString); 

        return preg_replace('&/{2,}&', '/', "$url");
    }    
       
    public function path($path = false){
        if (is_array($path)) {
			$path = implode('/', $path);
		}
		return preg_replace('&/{2,}&', '/', "./$path");
    }
	
	//ejecuta comando sql, y el resultado lo convierte a una clase
    public function query($query) {
		$query = dbquery($query); 
        $result = array();
        while ($result[] = @mysql_fetch_object($query)) {}	
	    
	    array_splice($result, count($result) - 1 );
	    
	    if (!$result) {
			throw new Exception(mysql_error());
	    } else {
		    return $result;
	    }
    }
    
	 //opterner todos los records del id del juego indicado
    public function getRec($game_id, $mode_id){
    
        $sql = <<<SQL
		SELECT 
			grs_records.id AS 'id',
			grs_modes.id AS 'mode_id',
			grs_players.name AS 'player',
			grs_cars.name AS 'car',
			grs_games.name AS 'game',
			grs_tracks.name AS 'track',
			grs_modes.name AS 'mode',
			grs_records.time AS 'time' 
		FROM 
			grs_records 
		JOIN grs_players ON grs_records.player_id = grs_players.id
		JOIN grs_cars ON grs_records.car_id = grs_cars.id
		JOIN grs_games ON grs_records.game_id = grs_games.id
		JOIN grs_tracks ON grs_records.track_id = grs_tracks.id
		JOIN grs_modes ON grs_records.mode_id = grs_modes.id
		WHERE grs_records.game_id='{$game_id}';
SQL;

        if($mode_id != 'all')
            $sql .= " AND grs_records.mode_id = '{$mode_id}';";
		
        return $this->query($sql);        
    }
    
    public function getGames(){
        return $this->query("SELECT * FROM grs_games");
    }    
    
    public function getModes(){
        return $this->query("SELECT id, name FROM grs_modes");   
    }
    
    public function getTracks(){
        return $this->query("SELECT id, name FROM grs_tracks");   
    }
    
    public function getCars($player_id){
        $sql = "SELECT id, name, player_id FROM grs_cars";
        
        if($player_id)
           $sql .= " WHERE player_id='{$player_id}'";
           
        return $this->query($sql);   
    }
    
    //opterner todos los modos de juegos que tenga al menos un record
    public function getModesWithRec($game_id){

        $modes = $this->getModes(); 
        
        //optener modos que se mostraran
        $modesToShow = @mysql_fetch_array(dbquery("SELECT mode_id FROM grs_records WHERE game_id ='{$game_id}'"));
        
        if($modesToShow){
            //remover modos sin records
            for($i=0;$i<=count($modes);$i++){
                if(!array_key_exists($modes[$i]->id, array_values($modesToShow)))
                    array_splice($modes, $i);           
            }
            
            return $modes;
        }
        
        //no se encontraro records para el game_id indicado
        return false;
    }
    
    
    public function getPlayerById($id){
		$results = $this->query("SELECT name FROM grs_players WHERE id='{$id}'");      
		return $results[0]->name;
    }
    
    public function getPlayerByName($name){
        if(!$name)
            return false;
            
        $results = $this->query("SELECT id FROM grs_players WHERE name='{$name}'");      
        return $results[0]->id;
    }
	
    public function getGameById($id){
        $sth = "SELECT name FROM grs_games WHERE id='{$id}'";
		
		$results = $this->query($sth);

        return $results[0]->name;
    }
    
    public function getModeById($id){
        $sth = "SELECT name FROM grs_modes WHERE id='{$id}'";
		
		$results = $this->query($sth);
        
		return $results[0]->name;
    }

}
?>